# -*- coding: utf-8 -*-
#
# Copyright © 2010 Benedikt Eger
#
# This file is part of top-news-buzz.
#
# top-news-buzz is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# top-news-buzz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with top-news-buzz.  If not, see <http://www.gnu.org/licenses/>.

import logging
import md5
import re

from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import DownloadError

from topnewsbuzz.metrics import MetricBase

class Metric(MetricBase):

    name = 'Delicious'

    def apply(self, news):
        # delicious.com metric
        url_md5 = md5.new(news.url).hexdigest()
        url = 'http://feeds.delicious.com/v2/json/urlinfo/' + url_md5
        try:
            result = urlfetch.fetch(url)
        except DownloadError:
            logging.error('Could not fetch url %s' % url)
            return 0.0
        if result.status_code == 200:
            match = re.match('.*"total_posts":(\d+).*', result.content)
            if match is not None:
                score = float(match.group(1))
                return score
        return 0.0
